/* Copyright (c) 2004-2023 Peigen.info. All rights reserved. */

package info.peigen.hotpot.manage.core.service.processor.user.check;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import info.peigen.hotpot.common.core.result.ResultCode;
import info.peigen.hotpot.common.core.util.PasswordUtils;
import info.peigen.hotpot.common.service.base.exception.BusinessException;
import info.peigen.hotpot.common.service.base.processor.Processor;
import info.peigen.hotpot.common.service.base.processor.ProcessorServiceContext;
import info.peigen.hotpot.manage.core.domain.User;
import info.peigen.hotpot.manage.core.service.order.UserEditOrder;
import info.peigen.hotpot.manage.core.service.processor.AbstractHotpotManageServiceProcessor;
import org.noear.solon.annotation.Component;

/**
 * <b>(UserEditCheckProcessor)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2023/8/30
 */
@Component
public class UserEditCheckProcessor extends AbstractHotpotManageServiceProcessor implements Processor {
    @Override
    public Integer level() {
        return 25;
    }

    @Override
    public void execute(ProcessorServiceContext serviceContext) {
        UserEditOrder order  = (UserEditOrder) serviceContext.getOrder();
        User          domain = (User) serviceContext.getDomain();
        checkPassword(order, domain);
        checkStatus(order, domain);
    }

    private void checkPassword(UserEditOrder order, User domain) {
        if (!StrUtil.isAllNotEmpty(order.getOldPassword(), order.getNewPassword(), order.getConfirmNewPassword())) {
            Assert.notEmpty(order.getOldPassword(), () -> new BusinessException(ResultCode.PARAMETER_ERROR, "老密码不得为空"));
            Assert.notEmpty(order.getNewPassword(), () -> new BusinessException(ResultCode.PARAMETER_ERROR, "新密码不得为空"));
            Assert.notEmpty(order.getConfirmNewPassword(), () -> new BusinessException(ResultCode.PARAMETER_ERROR, "新确认密码不得为空"));

            // 登陆密码与确认登录密码保持一致
            Assert.isTrue(StrUtil.equals(order.getNewPassword(), order.getConfirmNewPassword()), () -> new BusinessException(ResultCode.PW_AND_CONFIRMPW_IS_NOT_EQUALS));

            // 老密码不得与新密码一样
            Assert.isTrue(!StrUtil.equals(order.getOldPassword(), order.getNewPassword()), () -> new BusinessException(ResultCode.OLDPW_NEWPW_IS_EQUALS));

            // 老密码
            String oldPassword = PasswordUtils.generatePwdEncrypt(order.getOldPassword(), domain.getSalt(), domain.getCreateTime());
            Assert.isTrue(StrUtil.equals(domain.getPassword(), oldPassword), () -> new BusinessException(ResultCode.FAILURE, "老密码错"));
        }
    }

    private void checkStatus(UserEditOrder order, User domain) {
        if (ObjUtil.isNotEmpty(order.getStatus())) {
            domain.changeStatus(order.getStatus());
        }
    }

}
